from django.http import HttpResponseRedirect
from pyceab.plan.models import Plan
from django.core.urlresolvers import reverse

def get_plan_for_current_user(request):

    """
    Get the plan for the current user. Grab the plan
    id from the request session if it exists, otherwise traverse
    the relationships from request.user.
    """
    user = request.user
    if not user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.session.get('plan_id', False):
        plan = Plan.objects.get(pk=request.session['plan_id'])
    else:
        plan = user.student_set.get().plan_set.get()
        request.session['plan_id'] = plan.id
    return plan
